﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWebPagesStarterKit;
using MyWebPagesStarterKit.Controls;
using System.Data;

public partial class Administration_CustomHtml : PageBaseClass
{
    private CustomHtml _section;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            FillData();
    }

    private void FillData()
    {
        _section = CustomHtml.GetInstance();
        gwCHtml.DataSource = _section.Entries;
        gwCHtml.DataBind();
    }

    protected void Action(object sender, CommandEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
            ViewState["EditID"] = e.CommandArgument.ToString();

        _section = CustomHtml.GetInstance();

        switch (e.CommandName)
        {
            case "addHtml":
                    ViewState["EditID"] = null;
                    multiview.SetActiveView(view2);
                    txtTitle.Text = string.Empty;
                    txtHtml.Text = string.Empty;
                break;
            case "editHtml":
                    multiview.SetActiveView(view2);
                    DataRow row = _section.GetRowFromKey(Convert.ToString(ViewState["EditID"]));
                    txtTitle.Text = Convert.ToString(row["Title"]);
                    txtHtml.Text = Convert.ToString(row["Html"]);
                break;
            case "deleteHtml":
                    DataRow del = _section.GetRowFromKey(Convert.ToString(ViewState["EditID"]));
                    _section.Entries.Rows.Remove(del);
                    _section.Entries.AcceptChanges();
                    _section.SaveData();
                    ViewState["EditID"] = null;
                    Response.Redirect(Request.RawUrl);
                break;
            case "saveHtml":
                    Save();
                    ViewState["EditID"] = null;
                    multiview.SetActiveView(view1);
                break;
            case "cansel":
                ViewState["EditID"] = null;
                Response.Redirect(Request.RawUrl);
                break;
        }
    }

    private void Save()
    {

        if (string.IsNullOrEmpty(txtTitle.Text))
            return;

        DataRow row;

        if (ViewState["EditID"] == null)
        {
            row = _section.Entries.NewRow();
            row["Guid"] = Guid.NewGuid();
            _section.Entries.Rows.Add(row);
        }
        else
        {
            row = _section.GetRowFromKey(Convert.ToString(ViewState["EditID"]));
        }
        row["Title"] = txtTitle.Text;
        row["Html"] = txtHtml.Text;
        _section.Entries.AcceptChanges();
        _section.SaveData();
    }

}
